package com.galgram.web.controller.system;

import com.galgram.common.constant.Constants;
import com.galgram.common.core.domain.AjaxResult;
import com.galgram.common.core.domain.entity.SysMenu;
import com.galgram.common.core.domain.entity.SysUser;
import com.galgram.common.core.domain.entity.SysUserInfo;
import com.galgram.common.core.domain.model.LoginBody;
import com.galgram.common.utils.SecurityUtils;
import com.galgram.framework.web.service.SysLoginService;
import com.galgram.framework.web.service.SysPermissionService;
import com.galgram.system.service.ISysMenuService;
import com.galgram.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * 登录验证
 *
 * @author galgram
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 移动端登录登录方法
     *
     * @param phone 手机号
     * @return 结果
     */
    @GetMapping("/auth-login/{phone}")
    public AjaxResult authLogin(@PathVariable String phone) {
        AjaxResult ajax = AjaxResult.success();
        SysUserInfo userInfo = new SysUserInfo();
        if (phone != null) {
            if (phone.matches("^1[3-9]\\d{9}$")) {
                SysUser mobileUser = userService.selectUserByPhonenumber(phone);
                userInfo.setUserId(mobileUser.getUserId());
                userInfo.setUserName(mobileUser.getUserName());
                userInfo.setAvatar(mobileUser.getAvatar());
                userInfo.setNickName(mobileUser.getNickName());
                userInfo.setPhone(mobileUser.getPhonenumber());
                if (mobileUser != null) {
                    String token = loginService.login(mobileUser.getUserName(), "123456", "手机登录",
                            "手机uuid");
                    ajax.put(Constants.TOKEN, token);
                    ajax.put("userInfo", userInfo);
                    return ajax;
                } else {
                    SysUser user = new SysUser();
                    user.setPhonenumber(phone);
                    user.setNickName(phone.substring(0, 3) + "****" + phone.substring(7));
                    user.setUserName("用户" + UUID.randomUUID().toString().replace("-", "").substring(0, 10));
                    user.setPassword(SecurityUtils.encryptPassword("123456"));
                    userService.insertUser(user);
                    SysUser newUser = userService.selectUserByPhonenumber(phone);
                    String token = loginService.login(newUser.getUserName(), "123456", "手机登录", "手机uuid");
                    ajax.put(Constants.TOKEN, token);
                    ajax.put("userInfo", userInfo);
                    return ajax;
                }
            } else {
                return AjaxResult.error("登录失败");
            }
        } else {
            return AjaxResult.error("登录失败");
        }
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
